import Vue from 'vue'
import VueRouter from 'vue-router'

import store from "../store"

import Register from "../views/Register.vue"
import ImgInsert from "../views/ImgInsert.vue"
import IndexPage from "../views/IndexPage.vue"

import Classification from "../views/indexPage/Classification.vue"

import PersonalCenter from "../views/indexPage/PersonalCenter.vue"
import SignIn from "../views/indexPage/personalCenter/SignIn.vue"
import Works from "../views/indexPage/personalCenter/works.vue"
import Collection from "../views/indexPage/personalCenter/Collection.vue"
import Upload from "../views/upload.vue"

import Recommend from "../views/indexPage/Recommend.vue"
import Description from "../views/Description"

import {Token} from "../api/User.js"

Vue.use(VueRouter)

const originalPush=VueRouter.prototype.push

VueRouter.prototype.push=function push(location) {
    return originalPush.call(this,location).catch(err=>err)
}

const routes = [

  {path:"",redirect:"/recommend"},
  
  {path:"/imgInsert",component:ImgInsert,meta:{token:false}},//没啥用

  {path:"/signin",component:SignIn,meta:{token:false}},//登录
  {path:"/register",component:Register,meta:{token:true}},//
  {path:"/works",component : Works,meta:{token:true}},//我的作品
  {path:"/collection",component:Collection,meta:{token:true}},//收藏
  {path:"/upload",component : Upload,meta:{token:true}},//上传
  {path:"/description",component:Description,meta:{token:false}},//图片展示页面
  
  

  {path:"/indexPage",component :IndexPage,children:[
      {path:"/classification",component:Classification,meta:{token:false}},//分类
      {path:"/personalCenter",component:PersonalCenter,meta:{token:false}},//个人中心
      {path:"/recommend",component:Recommend,meta:{token:false}}//推荐

  ]},
]




const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach(async (to, from, next) => {
  if(localStorage.getItem("token")==null){
    store.commit("AlteruserName",{
        userId:-1,
        userName:"点击登录",
    })
  }
  


  if(to.matched[0].meta.token){
    let {data}=await Token()
    if(data.code==200){
      next()
    }else{
      next("/signin")
    }
  }
  next()

});

export default router
